'use strict';
var dayjs = require('dayjs')
var duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
module.exports = {
    /**
     * XXXnameXXX
     * @url client/booths/kh/getBoothsInfo 前端调用的url参数地址
     * data 请求参数
     * @param {String} params1  参数1
     */
    main: async (event) => {
        let {
            data = {}, userInfo, util, filterResponse, originalParam
        } = event;
        let {
            customUtil,
            uniID,
            config,
            pubFun,
            vk,
            db,
            _
        } = util;
        let {
            uid
        } = data;
        let res = {
            code: 0,
            msg: ""
        };
        let result = false;
        let {
            price,
            session_id,
            booth_id
        } = data;

        var $ = _.aggregate; // 聚合查询操作符
        let userbiddingbooths = await vk.baseDao.selects({
            dbName: "bidding-biddingprices", // 主表名
            getMain: true,
            whereJson: {
                userid: uid,
                status: _.neq(-1)
            },
            groupJson: {
                _id: "$booth_id",
                booth_id: $.first("$booth_id")
            },
        });
        let hasbiddingbooths = userbiddingbooths.map(x => x.booth_id);

        if (userbiddingbooths.length > 4 && !hasbiddingbooths.includes(booth_id)) {
            res.code = -1;
            res.msg = '你当前时段竞价展位已经达到5个!'
            return res;
        }

        let booth = await vk.baseDao.selects({
            dbName: "bidding-booths", // 主表名
            getOne: true, // 只返回第一条数据
            getMain: true,
            whereJson: {
                _id: booth_id,
            },
            // 副表列表
            foreignDB: [{
                dbName: "bidding-biddingprices", // 副表名
                localKey: "_id", // 主表外键字段名
                foreignKey: "booth_id", // 副表外键字段名
                as: "biddingList",
                limit: 10, // 当limit = 1时，以对象形式返回，否则以数组形式返回
                // 副表where条件
                whereJson: {
                    status: _.neq(-1)
                },
                // 副表字段显示规则
                fieldJson: {},
                // 副表排序规则
                sortArr: [{
                    "name": "_add_time",
                    "type": "desc"
                },
                {
                    "name": "price",
                    "type": "desc"
                }
                ],

            },
            {
                dbName: "bidding-session", // 副表名
                localKey: "location", // 主表外键字段名
                foreignKey: "place_id", // 副表外键字段名
                whereJson: {

                },
                as: "sessions",
                limit: 1000, // 当limit = 1时，以对象形式返回，否则以数组形式返回
            }
            ]
        });




        if (vk.pubfn.isNull(booth.status) || booth.status == 0 || booth.status == 1) {
            //未竞价或者已经竞价中
            if (!vk.pubfn.isNull(booth.sessions.find(x => x.status == 2))) {
                //当前时段有处于竞价状态的
                booth.session = booth.sessions.find(x => x.status == 2)
            } else if (vk.pubfn.isNotNull(vk.pubfn.isNull(booth.sessions.find(x => x.status == 3))) && vk.pubfn.isNotNull(booth.inLast) || booth.inLast) {
                //当前展位处于最后竞价时段并且该展位的竞价期已经结束
                booth.session = booth.sessions.find(x => x.status == 3)

            } else {

                res.code = -1;
                res.msg = '该展位已经竞价结束';
                return res;
            }
        } else {
            res.code = -1;
            res.msg = '该展位已经竞价结束';
            return res;
        }
        if (vk.pubfn.isNotNull(booth.biddingList[0])) {
            if (price < booth.biddingList[0].price) {
                res.code = -1;
                res.msg = `你的竞价低于当前价${vk.pubfn.priceFilter(booth.biddingList[0].price)},请重试`;
                res.nowPrice = booth.biddingList[0].price;
                res.biddingList = booth.biddingList;
                return res;
            } else if (price == booth.biddingList[0].price) {
                res.code = -1;
                res.msg = `你的出价已经给别人提前出了,当前价为${vk.pubfn.priceFilter(booth.biddingList[0].price)},请重试`;
                res.nowPrice = booth.biddingList[0].price;
                res.biddingList = booth.biddingList;
                return res;
            }
        }

        if (vk.pubfn.isNull(booth.endtime) && vk.pubfn.isNotNull(booth.session)) {
            const date1 = dayjs(new Date())
            const date2 = dayjs(booth.session.end)
            //最后5分钟不是自己出价
            if (dayjs.duration(date2.diff(date1)).as('minutes') < 5 && vk.pubfn.isNotNull(booth.biddingList) && booth.biddingList[0].userid != uid) {
                booth.endtime = vk.pubfn.getOffsetTime(new Date(), {
                    minutes: 5,
                    mode: "after", // after 之后 before 之前
                });
            } else {
                booth.endtime = booth.session.end;
            }
        } else {
            if (vk.pubfn.isNull(booth.inLast) || !booth.inLast) {
                const date1 = dayjs(new Date())
                const date2 = dayjs(booth.session.end)
                //最后5分钟并且上一个竞价人不是本人,进入延时阶段
                if (dayjs.duration(date2.diff(date1)).as('minutes') < 5 && vk.pubfn.isNotNull(booth.biddingList) && booth.biddingList[0].userid != uid) {
                    booth.endtime = vk.pubfn.getOffsetTime(new Date(), {
                        minutes: 5,
                        mode: "after",
                    });
                    booth.inLast = true;
                }
                else {
                    booth.endtime = booth.session.end;
                }
            } else {
                //进入最后竞价
                booth.endtime = vk.pubfn.getOffsetTime(new Date(), {
                    minutes: 5,
                    mode: "after",
                });
            }

        }


        const transaction = await vk.baseDao.startTransaction();
        try {
            let num = await vk.baseDao.updateById({
                db: transaction,
                dbName: 'bidding-booths',
                id: booth._id,
                dataJson: {
                    endtime: booth.endtime,
                    nowPrice: price,
                    inLast: booth.inLast,
                    status: 1
                }
            });
            let dbName = "bidding-biddingprices";
            res.id = await vk.baseDao.add({
                db: transaction,
                dbName,

                dataJson: {
                    userid: userInfo._id,
                    phone: vk.pubfn.hidden(userInfo.mobile, 0, 4),
                    full_mobile: userInfo.mobile,
                    price,
                    session_id,
                    booth_id
                }
            });
            await transaction.commit();
        } catch (err) {
            // 事务回滚
            await transaction.rollback();
            console.error(`transaction error`, err)
            return {
                code: -1,
                msg: "数据库写入异常,事务已回滚",
                err: {
                    message: err.message,
                    stack: err.stack
                }
            }
        }

        // 业务逻辑结束-----------------------------------------------------------
        return res;
    }
}